package com.zxjbyte.yiyi.framework.tenant.redis;

import cn.hutool.core.util.BooleanUtil;
import com.zxjbyte.yiyi.framework.common.constant.Constant;
import com.zxjbyte.yiyi.framework.common.constant.RedisKeyDefine;
import com.zxjbyte.yiyi.framework.common.constant.StringPool;
import com.zxjbyte.yiyi.framework.common.core.CacheKey;
import com.zxjbyte.yiyi.framework.tenant.config.TenantProperties;
import lombok.Getter;

import java.time.Duration;

/**
 *多租户拓展的 RedisKeyDefine 实现类
 *
 * 由于 Redis 不同于 MySQL 有 column 字段，无法通过类似 WHERE tenant_id = ? 的方式过滤
 * 所以需要通过在 Redis Key 上增加后缀的方式，进行租户之间的隔离。具体的步骤是：
 * 1. 假设 Redis Key 是 user:%d，示例是 user:1；对应到多租户的 Redis Key 是 user:%d:%d， 示例 user:1:000000
 * 2. 使用方式TenantRedisKeyDefine.getKey(Object... suffix)
 * @Author zhangxingjia
 * @Date 2023/4/3 15:28
 * @Version: 1.0
 */
public class TenantRedisKeyDefine extends RedisKeyDefine {

    /**
     * 多租户的 KEY 模板
     */
    private static final String DEFAULT_KEY_TEMPLATE_SUFFIX = StringPool.COLON + "%s";

    @Getter
    private static TenantRedisKeyDefine instance = null;

    private TenantProperties properties;

    public TenantRedisKeyDefine(TenantProperties properties){
        this.properties = properties;
        TenantRedisKeyDefine.instance = this;
    }


    public static CacheKey getObjectKey(Object... suffix){
        return TenantRedisKeyDefine.getObjectKey(null, suffix);
    }

    public static CacheKey getObjectKey(Duration expire, Object... suffix){
        return getInstance().buildCacheKey(expire, suffix);
    }

    public String getLastSuffix() {
        if(!BooleanUtil.isTrue(properties.getEnabled())){
            return StringPool.EMPTY;
        }
        return String.format(DEFAULT_KEY_TEMPLATE_SUFFIX, Constant.ADMIN_TENANT_ID);
    }
}
